package com.jf3q.common.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.tea.TeaModel;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod20170321.Client;
import com.aliyun.vod20170321.models.*;

import com.jf3q.common.ststem.Constant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadVideoService {

    @Value("${ali.endpoint}")
    String endpoint;
    @Value("${ali.bucketName}")
    String bucketName;
    @Value("${ali.accessKeyId}")
    String accessKeyId;
    @Value("${ali.secretAccessKey}")
    String secretAccessKey;

    @Autowired
    Client client;

    //阿里云文件上传
    public String upload(MultipartFile file, String type) {
        if (file == null || file.isEmpty()) {
            return "上传的文件为空";
        }

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        String dataPath = formatter.format(new Date());
        String fileName = dataPath + "/" + UUID.randomUUID().toString().replace("-", "") + suffix;

        StringBuffer objectName = new StringBuffer();

        switch (type) {
            case Constant.uploadType.AVATAR, Constant.uploadType.VIDEO, Constant.uploadType.COVER, Constant.uploadType.BANNER:
                objectName.append(type).append("/");
                break;
            default:
                return "类型错误";
        }

        objectName.append(fileName);


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);

        StringBuffer url = new StringBuffer();
        String str = endpoint.substring(endpoint.indexOf("o"));

        url.append("https://").append(bucketName).append(".").append(str)
                .append("/").append(type).append("/").append(fileName);
        try {
            ossClient.putObject(bucketName, objectName.toString(), file.getInputStream());
            return  url.toString();
        } catch (Exception e) {

            e.printStackTrace();
            return "上传云失败";
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    //阿里云oss对象文件删除
    public boolean delOssFile(String objectName){
        int index =0;
        if (objectName.contains("aliyuncs.com/")){
            index= objectName.indexOf("aliyuncs.com/")+13;
        }

        String name = objectName.substring(index);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);
        // 删除文件或目录。如果要删除目录，目录必须为空。
        try {
            ossClient.deleteObject(bucketName, name);
            return true;
        } catch (OSSException e) {
            throw new RuntimeException(e);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }


    //阿里云视频上传
    public String uploadVide(MultipartFile file) throws IOException {
        String title = file.getOriginalFilename();

        String fileName = title.substring(title.lastIndexOf("."));

        InputStream inputStream = file.getInputStream();

        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, secretAccessKey, title, fileName, inputStream);

        request.setCateId(1000580158L);

        //转码组id
        request.setTemplateGroupId("98cda69980016cb59c5850377652cc0a");

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);

        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            return response.getVideoId() ;
        } else {

            return response.getMessage();
        }
    }

    //获取阿里云视频地址
    public String getPlayUrl(@PathVariable String vid) {

        try {
            GetPlayInfoRequest request = new GetPlayInfoRequest();
            // 视频ID。
            request.videoId=vid;
            GetPlayInfoResponse responseGetPlayInfo = client.getPlayInfo(request);
            //将请求内容记录到日志
            com.aliyun.teaconsole.Client.log(Common.toJSONString(Common.toMap(responseGetPlayInfo)));

            String playURL = responseGetPlayInfo.getBody().getPlayInfoList().getPlayInfo().get(0).getPlayURL();
            return playURL;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    //获得播放凭证
    public String getPlayAuth(String vid) {
        try {
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest().setVideoId(vid);

            GetVideoPlayAuthResponse response = client.getVideoPlayAuthWithOptions(request, runtimeOptions);
            String playAuth = response.getBody().playAuth;
            com.aliyun.teaconsole.Client.log(Common.toJSONString(response));
            return playAuth;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


    //删除视频
    public String delVideo(String vid) {
        try {
            DeleteVideoRequest deleteVideoRequest = new DeleteVideoRequest().setVideoIds(vid);
            DeleteVideoResponse deleteVideoResponse = client.deleteVideo(deleteVideoRequest);
            com.aliyun.teaconsole.Client.log(Common.toJSONString(TeaModel.buildMap(deleteVideoResponse)));
            return "删除成功";
        } catch (Exception e) {
            //交给全局异常类处理
            throw new RuntimeException(e.getMessage()) ;
        }
    }
}
